﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading;
using System.Net;

namespace NotifierService.Client
{
    public partial class MainForm : Form
    {
        AudioTransmitter _transmitter;
        EasyClient _client;

        public MainForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //TODO: Replace by the correct uri address of the server
            EndpointAddress address = new EndpointAddress("net.tcp://localhost:8001/notifier");
            var binding = new NetTcpBinding();
            binding.ReliableSession.Enabled = true;
            binding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(25);
            ChannelFactory<Service.IServiceBase>.CreateChannel(binding, address);

            _client = new EasyClient(binding, address);
            _client.Open();


            while (_client.State != CommunicationState.Opened)
            {
                Thread.Sleep(50);
            }

            if(_client.Authenticate("admin", "admin"))
            {
                MessageBox.Show("User authenticated succeed.");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (button2.Text == "Start Broadcast")
            {
                var result = _client.StartRealtimeBroadcast();

                _transmitter = new AudioTransmitter(result.IsIPv6);
                if (result.IsIPv6)
                    //TODO: Replace by the correct ipv6 address of the server
                    _transmitter.Connect(IPAddress.IPv6Loopback, 80);
                else
                    //TODO: Replace by the correct ipv4 address of the server
                    _transmitter.Connect(IPAddress.Loopback, 80);

                button2.Text = "Stop Broadcast";
            }
            else
            {
                _transmitter.Stop();
                _client.StopRealtimeBroadcast();
                button2.Text = "Start Broadcast";
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            _client.PlayAudio(Service.AudioType.紧急集合号);
        }
    }
}
